var win = Ti.UI.currentWindow;
var data = [];

function getNow(){
	return Math.round(new Date().getTime() / 1000);
}

var actInd = Titanium.UI.createActivityIndicator({
	top:160, 
	height:60,
	width:60,
	style:Titanium.UI.iPhone.ActivityIndicatorStyle.BIG
});

//Ti.App.Properties.getList('noticies_list',[]);
//Ti.App.Properties.setList('noticies_list',dades);

Ti.include('dateFunctions.js');
Ti.include('dateFunctions2.js');

//var timestamp = Math.round(new Date().getTime() / 1000);
win.barColor='#333';
i18n = win.locales;
win.title = i18n.Bloc;

function getRow(id,tipus,title ,pubDate,link){
	var imatge='';

	/* 0 pirata.cat
	 * 1 youtube
	 * 2 flickr
	 * 3 nacionred
	 */
	switch(tipus){
		case 0:
			imatge='img/ic_info_bloc.png';
			break;
		case 1:
			imatge='img/ic_info_youtube.png';
			break;
		case 2:
			imatge='img/ic_info_flickr.png';
			break;
		case 3:
			imatge='img/ic_info_ppinternational.png';
			link =link.replace('www.nacionred', 'm.nacionred');
			break;
		
		default:
			imatge='img/ic_info_bloc.png';
			break;
	}
	
	var row = Ti.UI.createTableViewRow({
		height:60,
		opacity:0,
		backgroundColor:'transparent',
		borderWidth:0.0,
		leftImage:imatge,
		fontSize:"12",
		tipus:tipus,
		titol:title,
		pubDate:pubDate,
		link:link
		//title:title
	});

	var labelDate = Ti.UI.createLabel({
		left:50,
		text:pubDate,
		color:'#CCC',
		font:{fontSize:13}
	});
	var labelTitle = Ti.UI.createLabel({
		left:100,
		//backgroundColor:'#FFF',
		width:215,
		text:title,
		color:'#CCC',
		font:{fontSize:13}
	});
	row.add(labelDate,labelTitle);
	
	return row;
}

var tableview = Ti.UI.createTableView({
	//data:data,
	id:"tablaNoticias",
	//opacity:0,
	backgroundColor:'transparent',
	separatorStyle:0,
	maxRowHeigh:70,	
	minRowHeight:40
});
tableview.add(actInd);

tableview.addEventListener('click',function(e){
			
	var w = Ti.UI.createWindow({
		left:320,
		backgroundColor:'#000'
		
	});
	var vi = Ti.UI.createView({
		left:0,
		right:0,
		top:0,
		height:44,
		backgroundColor:'#3A3A3A'
	});
	
	var wb = Ti.UI.createWebView({top:44,backgroundColor:'#000'});
	if (e.row.tipus==1){
		wb.html='<html><head><meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=320"/></head><body style="background:#fff;margin-top:0px;margin-left:0px"><div><object width="320" height="150"><param name="movie" value="'+e.row.link+'"></param><param name="wmode" value="transparent"></param><embed src="'+e.row.link+'" type="application/x-shockwave-flash" wmode="transparent" width="320" height="150"></embed></object></div></body></html>';
	}else{
		wb.url=e.row.link;
	}

	//,
	var lab = Ti.UI.createLabel({
		text:e.row.titol,
		left:45,
		top:0,
		color:'#fff',
		font:{fontSize:12}
		//fontWeight:'bold',

	});
	
	vi.add(lab);
	var b = Ti.UI.createButton({
		left:5,
		top:5,
		height:33,
		width:33,
		//borderColor:'#ccc',
		//borderRadius:10,
		//borderWidth:2,
		backgroundColor:'#3A3A3A',
		color:'#000',
		title:'<',
		font:{fontSize:20},
		fontWeight:'bold',
		//systemButton:Ti.UI.iPhone.SystemButton.DONE
		style:Ti.UI.iPhone.SystemButtonStyle.BORDERED
	});
	//w.leftNavButton=b;
	vi.add(b);
	w.add(vi);
	//w.titleControl=vi;
	w.add(wb);
	b.addEventListener('click',function(){
		var slide_it_right = Ti.UI.createAnimation();
		slide_it_right.left = 320; // to put it back to the left side of the window
		slide_it_right.duration = 150;
		w.close(slide_it_right);
		});
	var slide_it_left = Ti.UI.createAnimation();
    slide_it_left.left = 0; // to put it back to the left side of the window
    slide_it_left.duration = 150;
	w.open(slide_it_left);
	
});


win.add(tableview);
win.backgroundImage='img/background2.png';
var xhr = Ti.Network.createHTTPClient(); //timeout
xhr.setTimeout(10000);
xhr.validatesSecureCertificate = false;

function setNews(noticies){
	var id;
	var newDate = new Date();
	var dateGroups = [];
	
    for(id in noticies)
    {
    	if (!isNaN(id))
        {
	    	var item = noticies[id];
			var title = item.title;
			var tipus = item.id;
			var pubDateStr = item.pubDate;
			var link = item.link;
			//Ti.API.info('"' + typeof id +'" -> tipus:' +tipus+' titol:'+title + ' date:'+pubDateStr+" link:"+link);
			newDate.setTime( pubDateStr*1000 );
			var dateString = newDate.getUTCDate() + ' ' + i18n.Month[newDate.getUTCMonth()];
			dateGroups.push(getRow(id,tipus,title,dateString,link));
        }
     }
    tableview.setData( dateGroups.reverse(),{ animationStyle : Titanium.UI.iPhone.RowAnimationStyle.DOWN });
}

function loadRSSFeed(xhr){
	var now = getNow();
	var last_news_date = Ti.App.Properties.getInt('last_news_date',now);
	
	if (Ti.Network.networkType == Ti.Network.NETWORK_NONE){
		alert(i18n.ConnectError);
		return;
	}
	
	if (   tableview.data==null || (last_news_date == now ||  now > (last_news_date + 300 ))){
		Ti.API.info('ha passat prou temps:'+(last_news_date == now));
		actInd.show();
		xhr.open("GET",win.config.url_rss);
		xhr.onload = function()
		{
			try
			{
				actInd.hide();
				var responseText = this.responseText;
				var noticies = JSON.parse(responseText);
				var x = 0;
				
				
				//Ti.App.Properties.getInt('last_news_date',now)
				setNews(noticies);
				Ti.App.Properties.setInt('last_news_date',now);
		
			}
			catch(err)
			{
				//alert(err.description);
				/*if (! xhr.connected ){
					alert(i18n.ConnectError);
				}*/
			}
		};
		xhr.send();
	}else{
		Ti.API.info('no ha passat prou temps:'+last_news_date + ' '+ now);
	}
}

//////////////////////////////////////////////////
var refresh = Ti.UI.createButton({systemButton:Ti.UI.iPhone.SystemButton.REFRESH});
refresh.addEventListener('click',function(){loadRSSFeed(xhr);});

Ti.App.addEventListener('resume', function(){
	loadRSSFeed(xhr)
});

Ti.UI.currentWindow.setLeftNavButton(refresh);
loadRSSFeed(xhr);